package xyz.lne.researchgroupmanage.controller;

import com.google.common.collect.ImmutableMap;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import xyz.lne.researchgroupmanage.annotation.AnonymousAccess;
import xyz.lne.researchgroupmanage.annotation.AnonymousGetMapping;
import xyz.lne.researchgroupmanage.annotation.AnonymousPostMapping;
import xyz.lne.researchgroupmanage.annotation.IgnoreResponseAdvice;
import xyz.lne.researchgroupmanage.common.CommonResponse;
import xyz.lne.researchgroupmanage.config.SecurityProperties;
import xyz.lne.researchgroupmanage.controller.request.AuthUserRequest;
import xyz.lne.researchgroupmanage.controller.request.UserRequest;
import xyz.lne.researchgroupmanage.exception.BadRequestException;
import xyz.lne.researchgroupmanage.security.OnlineUserService;
import xyz.lne.researchgroupmanage.security.TokenProvider;
import xyz.lne.researchgroupmanage.security.UserPower;
import xyz.lne.researchgroupmanage.service.dataTransferObject.JwtUserDTO;
import xyz.lne.researchgroupmanage.test.PowerTestRequest;
import xyz.lne.researchgroupmanage.util.SecurityUtils;
import xyz.lne.researchgroupmanage.util.enums.RequestMethodEnum;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Designed By Lne.
 * 2021/1/28 18:18
 */

@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthorizationController {
    private final SecurityProperties properties;
    private final TokenProvider tokenProvider;
    private final AuthenticationManagerBuilder authenticationManagerBuilder;
    private final PasswordEncoder passwordEncoder;
    private final OnlineUserService onlineUserService;


    @AnonymousPostMapping("/login")
    public Map<String, Object> login(@RequestBody AuthUserRequest authUserRequest){
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authUserRequest.getAccount(), authUserRequest.getPassword());
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = tokenProvider.createToken(authentication);
        final JwtUserDTO jwtUserDTO = (JwtUserDTO) authentication.getPrincipal();
        onlineUserService.save(jwtUserDTO, token);
        Map<String, Object> authUser = ImmutableMap.of("user", jwtUserDTO, "token", properties.getTokenStartWith() + token);
        return authUser;
    }


    @GetMapping("/logout")
    public CommonResponse logout(HttpServletRequest request){
//        if (!SecurityUtils.getCurrentUsername().equals(account))
//            throw new BadRequestException(ImmutableMap.of("account", account));
//        SecurityUtils.removeUserInCache(account);
        onlineUserService.logout(tokenProvider.getToken(request));
        return CommonResponse.create(CommonResponse.STATUS_SUCCESS);
    }

    @AnonymousPostMapping("/register")
    public AuthUserRequest register(@RequestBody UserRequest userRequest){
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userRequest.getAccount(), userRequest.getPassword());
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = tokenProvider.createToken(authentication);
        final JwtUserDTO jwtUserDTO = (JwtUserDTO) authentication.getPrincipal();
        return new AuthUserRequest("123", "999");
    }

//    测试token
    @IgnoreResponseAdvice
    @AnonymousPostMapping("/check")
    public String check(@RequestBody PowerTestRequest powerTestRequest){
        System.out.println(powerTestRequest);
        UserPower.check(powerTestRequest.getKind(), powerTestRequest.getId());
        return "accept!";
    }

    /**
     * 测试
     * @param s
     * @return
     */
    @AnonymousPostMapping("/test-anonymous")
    public String testa(@RequestParam String s){
        String psw = passwordEncoder.encode(s);
        String info = "before: " + s + "\nafter: " + psw;
        System.out.println(info);
        return info;
    }

    @PostMapping("/test")
    public String test(@RequestParam String s){
        String psw = passwordEncoder.encode(s);
        String info = "原始密码: " + s + "\n 加密后的: " + psw;
        System.out.println(info);
        return info;
    }

    // 跨域测试
    @AnonymousGetMapping("test-get")
    public String getTest(){
        String json = "{ \"stuId\": 1063, \"stuName\": \"毛爷爷\", \"password\": \"213312\", \"stuSex\": 1, \"stuBirthday\": \"2020-12-11\", \"stuInterest\": \"-3-5-\", \"stuEducation\": \"硕士\", \"stuPhone\": \"213\", \"stuEmail\": \"213\", \"stuAddress\": \"213\", \"myColor\": \"#cac8c4\", \"luckyNumber\": 213, \"reMark\": \"1231\", \"stuImageUrl\": \"IMG_20181010_113420.jpg\", \"clsid\": 1, \"power\": 1 }";
        return json;
    }
}
